package net

import (
	"data-system/models"
	"log"
	"math/rand"
	"sync"
	"time"

	"github.com/gorilla/websocket"
)

type Client struct {
	Id        string
	Conn      *websocket.Conn
	MsgChan   chan models.XMessage
	CloseChan chan struct{}
	Wg        sync.WaitGroup
}

func NewClient(conn *websocket.Conn) *Client {
	client := Client{
		Id:        generateClientID(),
		Conn:      conn,
		MsgChan:   make(chan models.XMessage, 100), // 缓冲队列
		CloseChan: make(chan struct{}),
	}
	return &client
}

func generateClientID() string {
	const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	// 生成一个足够长的随机字节切片来选择字母
	randomBytes := make([]byte, 8)
	_, err := rand.Read(randomBytes)
	if err != nil {
		panic(err)
	}
	b := make([]byte, 8)
	for i := range b {
		idx := int(randomBytes[i]) % len(letters)
		b[i] = letters[idx]
	}
	randomString := string(b)
	return "client-" + string(time.Now().Format("2006-01-02 15:04:05")+"-"+randomString)
}

func (c *Client) Start() {
	// 启动协程
	c.Wg.Add(3)
	go NewHeartbeat(c.Id, c.Conn, &c.Wg).Watch()
	go NewReceiver(c.Id, c.Conn, c.MsgChan, &c.Wg).Watch()
	go NewSender(c.Id, c.Conn, c.MsgChan, &c.Wg).Watch()
	// 等待连接关闭
	<-c.CloseChan
	c.Wg.Wait()
	c.Conn.Close()
	log.Println("连接关闭")
}
